package com.threadmethod.volatiled;

/**
 * @PackageName:com.threadmethod.volatiled
 * @ClassName:Test041
 * @Description:
 * @Author: zhangxiaoyu
 * @date 2020/12/10 15:13
 */
public class Test02 {

    public static void main(String[] args){
         //创建对象
        PrintString printString = new PrintString();
        //开启子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                printString.printStringMonth();
            }
        }).start();
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main打印标志");
        printString.setContinuePrint(false);
        
        //mian 线程修改了对象的打印标志后 而子线程读不到
        //解决办法：使用volatitle关键字  volatitle可以强制线程从公共内存中读取变量的值，而不是从工作内存中读取

    }


    //定义一个类
    static class PrintString{

        public void setContinuePrint(boolean continuePrint) {
            this.continuePrint = continuePrint;
        }

        //定义一个变量
        private volatile boolean continuePrint = true;


        public void printStringMonth(){

            System.out.println(Thread.currentThread().getName()+"开始。。。。");

            while (continuePrint){

            }
            
            System.out.println(Thread.currentThread().getName()+"结束----");
        }
    }

}
